package com.gulimall.order.web;

import com.common.constant.LoginConstant;
import com.common.to.MemberTo;
import com.gulimall.order.service.OrderWebService;
import com.gulimall.order.service.impl.OrderWebServiceImpl;
import com.gulimall.order.vo.OrderConfirmVo;
import com.gulimall.order.vo.OrderSubmitVo;
import com.gulimall.order.vo.SubmitOrderResponseVo;
import org.apache.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ExecutionException;

/**
 * @Author Rookie-6688
 * @Description
 * @Create 2021-04-27 16:42
 */
@Controller
public class OrderWebController {
    @Resource
    private OrderWebServiceImpl orderWebServiceImpl;

    /**
     * 去结算页面
     * @param request
     * @param model
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @GetMapping("/toTrade")
    public String toTrade(HttpServletRequest request, Model model) throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = orderWebServiceImpl.getOrderConfirm((MemberTo) request.getSession().getAttribute(LoginConstant.LOGIN_USERNAME));
        model.addAttribute("confirmOrderData",orderConfirmVo);
        return "confirm";
    }

    /**
     * 提交订单
     * @param orderSubmitVo
     * @param httpServletRequest
     * @param model
     * @return
     */
    @PostMapping("/submitOrder")
    public String submitOrder(OrderSubmitVo orderSubmitVo, HttpServletRequest httpServletRequest, Model model, RedirectAttributes redirectAttributes){
        SubmitOrderResponseVo submitOrderResponseVo = orderWebServiceImpl.submitOrder(orderSubmitVo, (MemberTo) httpServletRequest.getSession().getAttribute("loginUser"));
        if(submitOrderResponseVo.getCode()==0){
            // 没有任何异常
            model.addAttribute("submitOrderResp", submitOrderResponseVo);
            return "pay";
        }else{
            String msg = "下单失败";
            switch (submitOrderResponseVo.getCode()) {
                case 1: msg += "令牌订单信息过期，请刷新再次提交"; break;
                case 2: msg += "订单商品价格发生变化，请确认后再次提交"; break;
                case 3: msg += "库存锁定失败，商品库存不足"; break;
            }
            redirectAttributes.addFlashAttribute("msg",msg);
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }

}
